export default (app: any) => {
  app.directive("drag-modal", (el: any, binding: any, vnode: any) => {
    nextTick(() => {
      let modalEl: any = querySelector(`.${binding.value}.im-modal`);
      if (!modalEl) return;
      let headerEl = modalEl.querySelector(".im-modal-header");
      let left = 0;
      let top = 0;

      left = modalEl.left || 0;
      top = modalEl.top || 0;
      const handleMouseUp = (event: any) => {
        left = modalEl.left;
        top = modalEl.top;
        modalEl.onmousemove = null;
        modalEl.onmouseup = null;
        headerEl.releaseCapture && headerEl.releaseCapture();
      };
      headerEl.onmousedown = (e: { clientX: any; clientY: any }) => {
        let startX = e.clientX;
        let startY = e.clientY;
        headerEl.left = headerEl.offsetLeft;
        headerEl.top = headerEl.offsetTop;

        modalEl.onmousemove = (event: { clientX: any; clientY: any }) => {
          let endX = event.clientX;
          let endY = event.clientY;
          modalEl.left = headerEl.left + (endX - startX) + left;
          modalEl.top = headerEl.top + (endY - startY) + top;
          const screenX =
            (document.body.offsetWidth + 17 - modalEl.offsetWidth) / 2;
          const screenY =
            (document.body.offsetHeight - modalEl.offsetHeight) / 2;

          if (Math.abs(modalEl.left) > screenX) {
            if (modalEl.left < 0) {
              modalEl.style.left = -screenX + "px";
            }
            if (modalEl.left > 0) {
              modalEl.style.left = screenX + "px";
            }
          } else {
            modalEl.style.left = modalEl.left + "px";
          }
          if (Math.abs(modalEl.top) > screenY) {
            if (modalEl.top < 0) {
              modalEl.style.top = -screenY + "px";
            }
            if (modalEl.top > 0) {
              modalEl.style.top = screenY + "px";
            }
          } else {
            modalEl.style.top = modalEl.top + "px";
          }
        };

        modalEl.onmouseup = handleMouseUp;
        document.onmouseup = handleMouseUp;
        headerEl.setCapture && headerEl.setCapture();
        return false;
      };
    });
  });
};
